package com.ruoyi.web.service.Impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.web.domain.mes.*;
import com.ruoyi.web.domain.vo.MaterialRejectVo;
import com.ruoyi.web.domain.vo.MaterialReturnVo;
import com.ruoyi.web.mapper.MesMaterialInMapper;
import com.ruoyi.web.mapper.MesMaterialMapper;
import com.ruoyi.web.mapper.MesConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.mapper.MesMaterialRejectMapper;
import com.ruoyi.web.service.IMesMaterialRejectService;

import javax.annotation.Resource;

/**
 * 物料退货Service业务层处理
 *
 * @author levicash
 * @date 2024-01-30
 */
@Service
public class MesMaterialRejectServiceImpl implements IMesMaterialRejectService {
    @Resource
    private MesMaterialRejectMapper mesMaterialRejectMapper;

    @Resource
    private MesMaterialInMapper mesMaterialInMapper;

    @Resource
    private MesMaterialMapper mesMaterialMapper;

    @Resource
    private MesConfigMapper configMapper;

    /**
     * 查询物料退货
     *
     * @param id 物料退货主键
     * @return 物料退货
     */
    @Override
    public MesMaterialReject selectMesMaterialRejectById(Long id) {
        return mesMaterialRejectMapper.selectMesMaterialRejectById(id);
    }

    /**
     * 查询物料退货列表
     *
     * @param mesMaterialReject 物料退货
     * @return 物料退货
     */
    @Override
    public List<MesMaterialReject> selectMesMaterialRejectList(MesMaterialReject mesMaterialReject) {
        return mesMaterialRejectMapper.selectMesMaterialRejectList(mesMaterialReject);
    }

    /**
     * 新增物料退货
     *
     * @param mesMaterialReject 物料退货
     * @return 结果
     */
    @Transactional
    @Override
    public int insertMesMaterialReject(MesMaterialReject mesMaterialReject) {
        mesMaterialReject.setCreateTime(DateUtils.getNowDate());
        mesMaterialReject.setCreateBy(SecurityUtils.getUsername());
        // 生成退货单编号
        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "code");
        map.put("tableName", "mes_material_reject");
        int maxNum = configMapper.getMaxId(map);
        String code = PinYinUtils.getCodeNormal(maxNum, "WLRKD");
        mesMaterialReject.setCode(code);
        int rows = mesMaterialRejectMapper.insertMesMaterialReject(mesMaterialReject);
        insertMesMaterialRejectdetail(mesMaterialReject);
        return rows;
    }

    /**
     * 修改物料退货
     *
     * @param mesMaterialReject 物料退货
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMesMaterialReject(MesMaterialReject mesMaterialReject) {
        mesMaterialReject.setUpdateTime(DateUtils.getNowDate());
        mesMaterialReject.setUpdateBy(SecurityUtils.getUsername());
        int status = mesMaterialReject.getStatus();
        if (status == 1) {// 提交
            // 修改物料入库明细的仓库数量(减库存)
            MesMaterialReject Info = mesMaterialRejectMapper.selectMesMaterialRejectById(mesMaterialReject.getId()); // 查询数据库
            List<MesMaterialRejectdetail> mesMaterialRejectdetailList = Info.getMesMaterialRejectdetailList();
            if (mesMaterialRejectdetailList.size() > 0) {
                // 获取物料关联ids
                List<Long> listId = mesMaterialRejectdetailList.stream().map(it -> it.getMaterialId()).collect(Collectors.toList());
                Long[] ids = listId.toArray(new Long[0]);
                // 根据关联ids查询物料明细
                List<MesMaterial> detailList = mesMaterialMapper.selectMesMaterialByIds(ids);
                // 遍历明细修改库存
                for (MesMaterialRejectdetail mesMaterialRejectdetail : mesMaterialRejectdetailList) {
                    for (MesMaterial detailItem : detailList) {
                        if (detailItem.getId().equals(mesMaterialRejectdetail.getMaterialId())) {
                            BigDecimal stockNum = (detailItem.getQuantity() == null ? BigDecimal.ZERO : detailItem.getQuantity()); // 库存数量
                            BigDecimal quantity = mesMaterialRejectdetail.getQuantity(); // 退货数量
                            int result = stockNum.compareTo(quantity);
                            if (result < 0) {
                                throw new ServiceException("退货数量大于库存数量！");
                            } else {
                                BigDecimal difference = stockNum.subtract(quantity);
                                detailItem.setQuantity(difference);         // 更改库存数量
                                detailItem.setStockPrice(difference.multiply(detailItem.getRealtimePrice()));  // 更改金额
                            }
                        }
                    }
                }
                // 批量修改物料明细库存
                mesMaterialMapper.updateStockNumByBatch(detailList);
            }
        } else {
            mesMaterialRejectMapper.deleteMesMaterialRejectdetailByMaterialrejectId(mesMaterialReject.getId());
            insertMesMaterialRejectdetail(mesMaterialReject);
        }

        return mesMaterialRejectMapper.updateMesMaterialReject(mesMaterialReject);
    }

    /**
     * 批量删除物料退货
     *
     * @param ids 需要删除的物料退货主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesMaterialRejectByIds(Long[] ids) {
        mesMaterialRejectMapper.deleteMesMaterialRejectdetailByMaterialrejectIds(ids);
        return mesMaterialRejectMapper.deleteMesMaterialRejectByIds(ids);
    }

    /**
     * 删除物料退货信息
     *
     * @param id 物料退货主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesMaterialRejectById(Long id) {
        mesMaterialRejectMapper.deleteMesMaterialRejectdetailByMaterialrejectId(id);
        return mesMaterialRejectMapper.deleteMesMaterialRejectById(id);
    }

    /**
     * 新增物料退货明细信息
     *
     * @param mesMaterialReject 物料退货对象
     */
    public void insertMesMaterialRejectdetail(MesMaterialReject mesMaterialReject) {
        List<MesMaterialRejectdetail> mesMaterialRejectdetailList = mesMaterialReject.getMesMaterialRejectdetailList();
        Long id = mesMaterialReject.getId();
        if (StringUtils.isNotNull(mesMaterialRejectdetailList)) {
            List<MesMaterialRejectdetail> list = new ArrayList<MesMaterialRejectdetail>();
            for (MesMaterialRejectdetail mesMaterialRejectdetail : mesMaterialRejectdetailList) {
                mesMaterialRejectdetail.setCreateBy(SecurityUtils.getUsername());
                mesMaterialRejectdetail.setCreateTime(DateUtils.getNowDate());
                mesMaterialRejectdetail.setMaterialrejectId(id);
                list.add(mesMaterialRejectdetail);
            }
            if (list.size() > 0) {
                mesMaterialRejectMapper.batchMesMaterialRejectdetail(list);
            }
        }
    }

    /**
     * 查询物料退货明细
     *
     * @param map 查询参数
     * @return 物料退货关联集合
     */
    @Override
    public List<MaterialRejectVo> selectMesMaterialRejectDetailList(Map<String, Object> map) {
        return mesMaterialRejectMapper.selectMesMaterialRejectDetailList(map);
    }
}
